﻿using lottery.api.Models;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Threading.Tasks;

namespace lottery.api.Services
{
    public class WechatService: IWechatService
    {
        private readonly WechatOptions _option;
        private readonly ILogger _logger;
        private readonly HttpClient _client;

        public WechatService(IOptions<WechatOptions> option, ILogger<WechatService> logger, HttpClient client)
        {
            this._option = option.Value;
            this._logger = logger;
            this._client = client;
        }

        public async Task<SessionBody> GetSession(string code)
        {
            try
            {
                HttpResponseMessage sessionResp = await _client.GetAsync($"sns/jscode2session?appid={_option.Appid}&secret={_option.Secret}&js_code={code}&grant_type=authorization_code");
                var sessionBody = JsonConvert.DeserializeObject<SessionBody>(await sessionResp.Content.ReadAsStringAsync());
                if (!string.IsNullOrEmpty(sessionBody.errmsg))
                    throw new Exception(sessionBody.errmsg);

                return sessionBody;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"GetSession exception");
                if (ex.Message.Contains("The circuit is now open"))
                    throw ex;
                return null;
            }
        }
    }
}
